<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

/**
 *
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @package Simplify_Kernel
 */
final class Simplify
{

  /**
   *
   * @var IApplicationController
   */
  protected static $instance;

  protected static $config;
  
  /**
   * Constructor.
   *
   * @param Config $config
   * @return void
   */
  private function __construct()
  {
  }

  /**
   *
   * @return LanguageImpl
   */
  public static function getL10n()
  {
    return self::getInstance()->getL10n();
  }

  /**
   *
   * @return Config
   */
  public static function getConfig()
  {
    return self::getInstance()->getConfig();
  }

  /**
   *
   * @return IRouter
   */
  public static function getRouter()
  {
    return self::getInstance()->getRouter();
  }

  /**
   *
   * @return IRequest
   */
  public static function getRequest()
  {
    return self::getInstance()->getRequest();
  }

  /**
   *
   * @return IResponse
   */
  public static function getResponse()
  {
    return self::getInstance()->getResponse();
  }

  /**
   *
   *
   * @param string $app_dir the application directory
   * @return IApplicationController
   */
  public static function createInstance($app_dir)
  {
    self::$config = $config = new Config();

    $config->set('sy_dir', SY_DIR);
    $config->set('app_dir', sy_fix_path($app_dir));

    /**
     *
     * Absolute path to the web root
     *
     */
    $config->set('www_dir', sy_fix_path(dirname($_SERVER['SCRIPT_FILENAME'])));

    /**
     *
     * Absolute path to public files
     *
     */
    $config->set('files_dir', '{www_dir}/files');

    /**
     *
     * Base URL and protocol
     *
     */
    $secure = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $config->set('url_protocol',
        substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0,
            strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $secure);
    $config->set('base_url', $config->get('url_protocol') . '://' . $_SERVER['HTTP_HOST']);

    if (isset($_SERVER['ORIG_SCRIPT_NAME'])) {
      $config->set('app_url',
          preg_replace('#/$#', '', $config->get('base_url') . dirname($_SERVER['ORIG_SCRIPT_NAME'])));
    }
    else {
      $config->set('app_url', preg_replace('#/$#', '', $config->get('base_url') . dirname($_SERVER['SCRIPT_NAME'])));
    }

    if (file_exists($config->get('app_dir') . '/config.yml')) {
      $config->copyAllFromYAMLFile($config->get('app_dir') . '/config.yml');
    }

    /**
     *
     * instantiate core classes
     *
     */

    $class = $config->get('core:app:class', 'ApplicationControllerImpl');
    $app = self::$instance = new $class($config);

    $class = $config->get('core:router:class', 'AutoRouterImpl');
    $app->setRouter(new $class());

    $class = $config->get('core:request:class', 'RequestImpl');
    $app->setRequest(new $class());

    $class = $config->get('core:l10n:class', 'LanguageImpl');
    $app->setL10n(new $class());

    $app->initialize();
    $app->getRouter()->initialize();
    $app->getRequest()->initialize();
    $app->getL10n()->initialize();

    return self::$instance;
  }

  public static function autoload($class_name)
  {
    $classPath = array(
      '', 'kernel', 'kernel/api', 'kernel/core', 'kernel/data', 'kernel/data/api', 'kernel/data/filter',
      'kernel/data/validation', 'kernel/data/filter/api', 'kernel/data/validation/api', 'kernel/view',
      'kernel/cache', 'kernel/domain', 'kernel/dao', 'lib'
    );

    foreach ($classPath as $path) {
      if (file_exists(SY_DIR . '/' . $path . '/' . $class_name . '.php')) {
        require_once (SY_DIR . '/' . $path . '/' . $class_name . '.php');
        return;
      }
    }

    $app_class_path = Config::parseFrom(self::$config->get('app_class_path'))->getAll();

    foreach ($app_class_path as $path) {
      if (file_exists($path . '/' . $class_name . '.php')) {
        require_once ($path . '/' . $class_name . '.php');
        return;
      }
    }
  }

  /**
   *
   * @return IApplicationController
   */
  public static function getInstance()
  {
    if (empty(self::$instance)) {
      throw new Exception('You must create an instance of the application with Simplify::createInstance($app_dir) before getting it.');
    }

    return self::$instance;
  }

}

?>